package com.antdesignbackend.backend.controller;

import com.alibaba.excel.metadata.Sheet;
import com.antdesignbackend.backend.animalNumber.entity.AnimalNumber;
import com.antdesignbackend.backend.animalNumber.service.AnimalNumberService;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.excel.ExcelUtil;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Production;
import com.antdesignbackend.backend.entity.Reproduction;
import com.antdesignbackend.backend.entity.entityVo.ProductionVo;
import com.antdesignbackend.backend.entity.entityVo.ReproductionVo;
import com.antdesignbackend.backend.service.ProductionService;
import com.antdesignbackend.backend.service.ReproductionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/reproduction")
@Controller
public class ReproductionController extends BaseController {

    @Autowired
    ReproductionService reproductionService;
    @Autowired
    AnimalNumberService animalNumberService;
    @Autowired
    ProductionService productionService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;

    @GetMapping("/index")
    @AuthToken
    public String ProductionIndex() {
        return "records/reproduction/index";
    }

    /**
     * 分页查询
     * @param
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody ReproductionVo reproductionVo) {
        ReturnVO result = new ReturnVO();
        List<ReproductionVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<ReproductionVo> queryWrapper = new QueryWrapper<>();
            if (reproductionVo.getLivestockNumber() != null && !reproductionVo.getLivestockNumber().equals("")){
                queryWrapper.like("livestockNumber",reproductionVo.getLivestockNumber());
            }
            if (reproductionVo.getTimeInterval() != null && !reproductionVo.getTimeInterval().equals("")){
                String[] str=reproductionVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("breedingTime",star,end);
            }
            if (reproductionVo.getTimeInterval2() != null && !reproductionVo.getTimeInterval2().equals("")){
                String[] str=reproductionVo.getTimeInterval2().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("productionTime",star,end);
            }
            if (reproductionVo.getFormulation() != null && !reproductionVo.getFormulation().equals("")){
                queryWrapper.eq("formulation",reproductionVo.getFormulation());
            }
            if (reproductionVo.getChildbirth() != null){
                if (reproductionVo.getChildbirth() == 0){
                    queryWrapper.eq("a.state",1).isNull("deliveryTime");
                }else {
                    queryWrapper.isNotNull("deliveryTime");
                }
            }
            queryWrapper.orderByDesc("breedingTime").orderByDesc("a.createTime");
            queryWrapper.eq("a.eid",getLoginEnterpriseId());
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=reproductionService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= reproductionService.search(queryWrapper,new Page<>(reproductionVo.getPageIndex(),reproductionVo.getPageSize()));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    @PostMapping("/tableSearchMe")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearchMe(@RequestBody ReproductionVo reproductionVo) {
        ReturnVO result = new ReturnVO();
        List<ReproductionVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<ReproductionVo> queryWrapper = new QueryWrapper<>();
            if (reproductionVo.getLivestockNumber() != null && !reproductionVo.getLivestockNumber().equals("")){
                queryWrapper.like("livestockNumber",reproductionVo.getLivestockNumber());
            }
            if (reproductionVo.getFormulation() != null && !reproductionVo.getFormulation().equals("")){
                queryWrapper.eq("formulation",reproductionVo.getFormulation());
            }
            if (reproductionVo.getChildbirth() != null){
                if (reproductionVo.getChildbirth() == 0){
                    queryWrapper.eq("a.state",1).isNull("deliveryTime");
                }else {
                    queryWrapper.isNotNull("deliveryTime");
                }
            }
            queryWrapper.orderByDesc("breedingTime").orderByDesc("a.createTime");
            queryWrapper.eq("a.eid",reproductionVo.getEid());
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=reproductionService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= reproductionService.search(queryWrapper,new Page<>(1,10));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody Reproduction reproduction) throws Exception {

        /**
         * 将该母畜编号所有state改为0
         */
        UpdateWrapper<Reproduction> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("state",0).eq("state",1).eq("livestockNumber",reproduction.getLivestockNumber());
        reproductionService.update(updateWrapper);
        reproduction.setState(1);
        ReturnVO result = new ReturnVO();
        boolean b = false;
        if(reproduction.getReproductionId()==null ||reproduction.getReproductionId()==0){
            QueryWrapper<Reproduction> reproductionQueryWrapper=new QueryWrapper<>();
            reproductionQueryWrapper.eq("livestockNumber",reproduction.getLivestockNumber()).eq("eid",getLoginEnterpriseId()).isNotNull("DeliveryTime");
            Integer parity=reproductionService.count(reproductionQueryWrapper);

            QueryWrapper<Reproduction> reproductionQueryWrapper1=new QueryWrapper<>();
            reproductionQueryWrapper1.eq("livestockNumber",reproduction.getLivestockNumber()).eq("eid",getLoginEnterpriseId())
                    .orderByDesc("BreedingTime").orderByDesc("createTime");
            List<Reproduction> list = reproductionService.list(reproductionQueryWrapper1);
            int a = 1; //配种次数
            int c = 0; //是否复配
            if (!list.isEmpty()){
                Reproduction reproduction1 = list.get(0);
                if (reproduction1.getDeliveryTime() ==null){
                    a = reproduction1.getMateNumber() + 1;
                    c = 1;
                }
            }
            reproduction.setMateNumber(a);
            reproduction.setFormulation(c);
            reproduction.setParity(parity);
            reproduction.setUid(getLoginUserId());
            reproduction.setCreateTime(new Date());
            reproduction.setEid(getLoginEnterpriseId());
            reproduction.setAnimalType(getLoginAnimal());
            Calendar cld = Calendar.getInstance();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            String oldTime=sdf.format(reproduction.getBreedingTime());
            String[] str=oldTime.split("-");
            cld.set(Calendar.YEAR, Integer.parseInt(str[0]));
            cld.set(Calendar.MONDAY,Integer.parseInt(str[1]));
            cld.set(Calendar.DATE,Integer.parseInt(str[2]));
            cld.add(Calendar.DATE, getBirthDay());
            String newTime=cld.get(Calendar.YEAR)+"-"+cld.get(Calendar.MONTH)+"-"+cld.get(Calendar.DATE);
            reproduction.setProductionTime(sdf.parse(newTime));

            b=reproductionService.save(reproduction);
        }else{
            b=reproductionService.updateById(reproduction);
        }
        //分娩完成,自动生成一条动物明细记录，并自动生成一条进厂记录
        if(reproduction.getLiveNumber()!=null){
            System.out.println("母畜种类是啊"+reproduction.getMatherType());
            //新增一条动物明细记录
            AnimalNumber animalNumber=new AnimalNumber();
            animalNumber.setEid(getLoginEnterpriseId());
            animalNumber.setLactation(reproduction.getLiveNumber());
            animalNumber.setAnimalType(getLoginAnimalTypes());
            animalNumber.setStarTime(reproduction.getDeliveryTime());
            animalNumber.setConservationTime(CalendarDate.addDate(animalNumber.getStarTime(),"day",getDay1()));
            animalNumber.setGrowTime(CalendarDate.addDate(animalNumber.getStarTime(),"day",getDay1()+getDay2()));
            animalNumber.setCreateTime(new Date());
            animalNumber.setChannel(3);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            animalNumber.setBatchNumber(simpleDateFormat.format(animalNumber.getStarTime()));
            animalNumber.setPid(reproduction.getReproductionId());
            animalNumberService.save(animalNumber);
            if(reproduction.getMatherType().equals("后备母畜")){
                QueryWrapper<AnimalNumber> animalNumberQueryWrapper=new QueryWrapper<>();
                animalNumberQueryWrapper.eq("channel",1).eq("eid",getLoginEnterpriseId());
                AnimalNumber oldAnimalNumber=animalNumberService.getOne(animalNumberQueryWrapper);
                System.out.println("老后备为"+oldAnimalNumber.getReserve()+"老能繁为"+oldAnimalNumber.getMenstruation());
                UpdateWrapper<AnimalNumber> animalNumberUpdateWrapper=new UpdateWrapper<>();
                animalNumberUpdateWrapper.set("reserve",oldAnimalNumber.getReserve()-1).set("menstruation",oldAnimalNumber.getMenstruation()+1)
                        .eq("channel",1).eq("eid",getLoginEnterpriseId());
                animalNumberService.update(animalNumberUpdateWrapper);
            }
            //新增一条进厂记录
            Production production=new Production();
            production.setUid(getLoginUserId());
            production.setEid(getLoginEnterpriseId());
            production.setChangeTime(reproduction.getDeliveryTime());
            production.setSituation("出生");
            production.setAnimalType(getLoginAnimal());
            production.setLactation(reproduction.getLiveNumber());
            production.setCreateTime(new Date());
            productionService.save(production);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 删除
     * @param
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        ReturnVO result = new ReturnVO();
        if (reproductionService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
        } else {
            result.setMessage("删除失败");
            result.setCode("0");
        }
        return result;
    }
    /***
     * 上传文件
     * @return
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request) throws Exception {
        Integer successnum = 0;
        long random = System.currentTimeMillis();
        String dateKey = random + "";
        String localPathDir = "";
        String newFileName = "";
        if (!WebConfig.uploadunicomphonefile.equals("")) {
            localPathDir = WebConfig.uploadunicomphonefile;
        } else {
            localPathDir = ResourceUtils.getURL("classpath:").getPath() + "unicomphone/";
        }
        File logoSaveFile = new File(localPathDir);
        if (!logoSaveFile.exists()) {
            logoSaveFile.mkdirs();
        }
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            Iterator iter = mr.getFileMap().values().iterator();
            if (iter.hasNext()) {
                MultipartFile file = (MultipartFile) iter.next();
                String oname = file.getOriginalFilename();
                String fileTyle = oname.substring(oname.lastIndexOf("."), oname.length());
                fileTyle = fileTyle.toLowerCase();
                newFileName = dateKey + fileTyle;
                String fileName = localPathDir + newFileName;
                if (fileTyle.equals(".xlsx") || fileTyle.equals(".xls") || fileTyle.equals(".XLSX") || fileTyle.equals(".XLS")) {
                    InputStream inputstream = file.getInputStream();
                    byte[] bytes = new byte[1024];
                    FileOutputStream outstream = new FileOutputStream(fileName);
                    int index;
                    while ((index = inputstream.read(bytes)) != -1) {
                        outstream.write(bytes, 0, index);
                        outstream.flush();
                    }
                    outstream.close();
                    inputstream.close();
                }
            }
        }
        try {
            System.out.println("进入批量导入方法");
            String filePath = localPathDir + "" + newFileName;
            Sheet sheet = new Sheet(1, 2);
            List<Object> objects = ExcelUtil.readLessThan1000RowBySheet(filePath, sheet);
            if (objects.size() > 0) {
                for (int k = 0; k < objects.size(); k++) {
                    String livestockNumber = "";	//母畜编号
                    String matherType = "";		//母畜类型
                    String breedingTime;	//配种时间
                    String parity = "";		//胎次
                    String mateNumber = "";		//配种次数
                    ArrayList arr = (ArrayList) objects.get(k);
                    if (((ArrayList) objects.get(k)).get(0).toString().equals("") && ((ArrayList) objects.get(k)).get(0).toString()==null){
                        continue;
                    }
                    if (((ArrayList) objects.get(k)).get(1).toString().equals("") && ((ArrayList) objects.get(k)).get(0).toString()==null){
                        continue;
                    }
                    if (((ArrayList) objects.get(k)).get(2).toString().equals("") && ((ArrayList) objects.get(k)).get(0).toString()==null){
                        continue;
                    }
                    if (((ArrayList) objects.get(k)).get(3).toString().equals("") && ((ArrayList) objects.get(k)).get(0).toString()==null){
                        continue;
                    }
                    if (((ArrayList) objects.get(k)).get(4).toString().equals("") && ((ArrayList) objects.get(k)).get(0).toString()==null){
                        continue;
                    }
                    livestockNumber = ((ArrayList) objects.get(k)).get(0).toString();
                    matherType = ((ArrayList) objects.get(k)).get(1).toString();
                    breedingTime = ((ArrayList) objects.get(k)).get(2).toString();
                    parity = ((ArrayList) objects.get(k)).get(3).toString();
                    mateNumber = ((ArrayList) objects.get(k)).get(4).toString();
                    QueryWrapper<Reproduction> wrapper = new QueryWrapper<>();
                    Reproduction reproduction=new Reproduction();
                    //新增
                    reproduction.setLivestockNumber(livestockNumber);
                    reproduction.setMatherType(matherType);
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
                    reproduction.setBreedingTime(simpleDateFormat.parse(breedingTime));
                    reproduction.setParity(Integer.valueOf(parity));
                    reproduction.setMateNumber(Integer.valueOf(mateNumber));
                    //默认值
                    reproduction.setEid(getLoginEnterpriseId());
                    reproduction.setAnimalType(getLoginAnimal());
                    Calendar cld = Calendar.getInstance();
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                    String oldTime=sdf.format(reproduction.getBreedingTime());
                    String[] str=oldTime.split("-");
                    cld.set(Calendar.YEAR, Integer.parseInt(str[0]));
                    cld.set(Calendar.MONDAY,Integer.parseInt(str[1]));
                    cld.set(Calendar.DATE,Integer.parseInt(str[2]));
                    cld.add(Calendar.DATE, getBirthDay());
                    String newTime=cld.get(Calendar.YEAR)+"-"+cld.get(Calendar.MONTH)+"-"+cld.get(Calendar.DATE);
                    reproduction.setProductionTime(sdf.parse(newTime));
                    reproduction.setUid(getLoginUserId());
                    reproduction.setCreateTime(new Date());
                    if(reproductionService.save(reproduction)){
                        successnum = successnum + 1;
                    };
                }
            }
        } catch (Exception ex) {
            logger.error("上传错误：" + ex.getMessage());
        }
        return "成功上传：" + successnum;
    }
}
